package com.rongshu.view.userInfo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.userInfo.adapter.DirectChatAdapter;
import com.rongshu.view.userInfo.entity.DirectChat;
import com.rongshu.view.userInfo.entity.DirectMessage;
import com.rongshu.view.userInfo.entity.sixinClass;
import com.rongshu.view.userInfo.iview.DirectChatView;
import com.rongshu.view.userInfo.presenter.DirectChatPresenter;
import com.rongshu.widget.BanyanDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.FastClickUtils;
import com.widget.popupwindow.ArticleStatusPopupWindow;
import com.widget.titlebar.ImmersionBar;
import com.widget.titlebar.OnKeyboardListener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class DirectChatActivity extends BaseActivity<DirectChatPresenter> implements DirectChatView {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.layout_menu)
    LinearLayout layout_menu;
    @BindView(R.id.chat_recyclerview)
    RecyclerView chat_recyclerview;
    @BindView(R.id.smartRefreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.edt_chat_input)
    EditText edt_chat_input;

    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private DirectChatAdapter adapter = null;
    //intent
    private Intent intent = null;
    //聊天人信息
    private DirectMessage.ResponseBean responseBean = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //boolean
    private boolean isFresh = false;
    //dialog 加入黑名单提示用
    private BanyanDialog banyanInputDialog = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset().keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        if (isPopup) {
                            chat_recyclerview.scrollToPosition(adapter.getItemCount() - 1);
                        }
                    }
                });
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .init();  //必须调用方可沉浸式
        } else {
            bar.flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f)
                    .init();  //必须调用方可沉浸式
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_direct_chat_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new DirectChatPresenter(this), this);
        //intent
        intent = getIntent();
        responseBean = (DirectMessage.ResponseBean) intent.getSerializableExtra(Constant.INTENT_DATA);
        if (responseBean != null) {
            txt_top_title.setText(responseBean.getBi_name());
        }
        layout_menu.setVisibility(View.GONE);
        //manager
        manager = new LinearLayoutManager(this);
        //adapter
        adapter = new DirectChatAdapter(this);
        //recyclerview
        chat_recyclerview.setLayoutManager(manager);
        chat_recyclerview.setAdapter(adapter);
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                if (responseBean != null) {
                    isFresh = false;
                    pageIndex++;
                    getReceiveMessage(responseBean.getNewSend_userid());
                    refreshlayout.finishRefresh(5000, true);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        if (responseBean != null) {
            isFresh = true;
            pageIndex = 1;
            getReceiveMessage(responseBean.getNewSend_userid());
            isAtUserDisabled(responseBean.getNewSend_userid());
        }
    }

    /**
     * 私信消息列
     */
    private void getReceiveMessage(int send_userid) {
        //user_id
        int receive_userid = getUserId();
        map = new HashMap<>();
        map.put("send_userid", receive_userid);
        map.put("receive_userid", send_userid);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getReceiveMessage(receive_userid, send_userid,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 私信消息
     */
    private void postSendMessage(int receive_userid, String content) {
        //user_id
        int send_userid = getUserId();
        map = new HashMap<>();
        map.put("send_userid", send_userid);
        map.put("receive_userid", receive_userid);
        //content
        sixinClass sixinClass = new sixinClass();
        try {
            content = URLEncoder.encode(content, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sixinClass.setContent(content);
        presenter.postSendMessage(send_userid, receive_userid, Common.encryptionSign(map), sixinClass);
        map.clear();
    }

    /**
     * 加入黑名单
     */
    private void blackListOption(int user_id_to) {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("user_id_to", user_id_to);
        presenter.blackListOption(
                (int) map.get("user_id"),
                (int) map.get("user_id_to"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 判断用户是否被禁用
     */
    private void isAtUserDisabled(int user_id_to) {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("user_id_to", user_id_to);
        presenter.isAtUserDisabled(
                (int) map.get("user_id"),
                (int) map.get("user_id_to"),
                Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back, R.id.layout_menu, R.id.txt_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                onBackPressed();
                break;
            case R.id.layout_menu://功能
                View view1 = new ArticleStatusPopupWindow(this, R.layout.dialog_toreport_the_blacklist, 120)
                        .showAtBottom(view);
                LinearLayout layout_toreport = view1.findViewById(R.id.layout_toreport);
                LinearLayout layout_blacklist = view1.findViewById(R.id.layout_blacklist);
                layout_toreport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (responseBean != null) {
                            Intent intent = new Intent(DirectChatActivity.this, ToReportActivity.class);
                            intent.putExtra(Constant.INTENT_MESSAGE, responseBean.getSend_userid());
                            intent.putExtra(Constant.INTENT_TYPE, 2);
                            startActivity(intent);
                        }
                    }
                });
                layout_blacklist.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showAddBlackHint();
                    }
                });
                break;
            case R.id.txt_send://发送
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                String content = edt_chat_input.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    toast("不能发送空消息");
                    return;
                }
                if (responseBean != null) {
                    postSendMessage(responseBean.getNewSend_userid(), content);
                }
                break;
        }
    }

    /**
     * 提示加入黑名单
     */
    public void showAddBlackHint() {
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("提示");
        builder.setContent("是否将此人加入黑名单");
        builder.setLeft("取消");
        builder.setRight("确定");
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                banyanInputDialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                banyanInputDialog.dismiss();
                if (responseBean != null) {
                    blackListOption(responseBean.getSend_userid());
                }
            }
        });
        banyanInputDialog = builder.create();
        banyanInputDialog.show();
    }

    /**
     * 私信消息列
     */
    @Override
    public void onDirectChatMsg(DirectChat chat) {
        if (chat == null) {
            return;
        }
        edt_chat_input.requestFocus();
        edt_chat_input.setFocusableInTouchMode(true);
        edt_chat_input.setFocusable(true);
        List<DirectChat.ResponseBean> directChatResponseList = chat.getResponse();
        refreshLayout.finishRefresh();
        if (!isFresh) {
            directChatResponseList.addAll(adapter.getDirectChatList());
        }
        adapter.setDirectChatList(directChatResponseList);
        adapter.notifyDataSetChanged();
        if (isFresh) {
            chat_recyclerview.scrollToPosition(adapter.getItemCount() - 1);
        }
        if (directChatResponseList != null) {
            if (directChatResponseList.size() > 0) {
                for (DirectChat.ResponseBean bean : directChatResponseList) {
                    if (bean.getSend_userid() != UserInfoUtils.getUserId()) {
                        txt_top_title.setText(bean.getBi_name());
                        break;
                    }
                }
            }
        }
    }

    /**
     * 发送私信消息
     *
     * @param bean
     */
    @Override
    public void onDirectChatSendMsg(INetBean bean) {
        if (bean.getErrCode() == 0) {
            if (responseBean == null) {
                return;
            }
            isFresh = true;
            pageIndex = 1;
            refreshLayout.resetNoMoreData();
            getReceiveMessage(responseBean.getNewSend_userid());
            edt_chat_input.setText("");
        } else {
            toast(bean.getErrMsg());
        }
    }

    /**
     * 加入黑名单
     */
    @Override
    public void onUserAddBlack(INetBean bean) {
        toast(bean.getErrMsg());
    }

    @Override
    public void onBackPressed() {
        List<DirectChat.ResponseBean> beans = adapter.getDirectChatList();
        if (beans != null && beans.size() > 0) {
            Intent intent = new Intent();
            intent.putExtra(Constant.INTENT_DATA, beans.get(beans.size() - 1).getContents());
            intent.putExtra(Constant.INTENT_MESSAGE, beans.get(beans.size() - 1).getCreate_datetime());
            setResult(RESULT_OK, intent);
        }
        showKeyboard(false);
        super.onBackPressed();
    }
}
